from django.shortcuts import render
from crouse.models import CategoryModel,CourseModel,TeacherModel
from crouse.ser import CateSerializer,Category,CourseSerializer,CourseListSerializer,BannerImage,CourseIndexSer
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from django.db.models import Q
from drf_haystack.viewsets import HaystackViewSet
from utils.myedis import redistoll

class CoursePage(PageNumberPagination):
    page_size=3
    page_size_query_param = 'size'
    page_query_param = 'page'
class CateGoryView(APIView):
    def get(self,request):
        data=CategoryModel.objects.filter(parent=None,ishome=True,isshow=True)
        ser=CateSerializer(data,many=True)
        for i in ser.data:
            i['child']=i['child'][:3]
        return Response({'mas':'success','data':ser.data,'code':200})

class NowCate(APIView):
    def get(self,request):
        id =request.query_params.get('id')
        info=CategoryModel.objects.filter(id=id,parent=None,ishome=True,isshow=True).first()
        ser=CateSerializer(info)
        twocate=CategoryModel.objects.filter(parent=id,isshow=True).values_list('id',flat=True)
        course=CourseModel.objects.filter(catetegory__in=twocate,isshow=True,ishome=True).order_by('order').values()[:4]
        courseinfo=ser.data
        courseinfo['course']=course
        return Response({'mas':'success','data':courseinfo,'code':200})

class Direction(APIView):
    def get(self,request):
        allcate=CategoryModel.objects.filter(parent=None,isshow=True).order_by('order')
        ser=Category(allcate,many=True)
        return Response({'mas':'success','data':ser.data,'code':200})

class ChildCate(APIView):
    def get(self,request):
        pid =str(request.query_params.get('pid'))
        if pid=="0":
            child=CategoryModel.objects.exclude(parent=None).order_by('order')
        else:
            child=CategoryModel.objects.filter(parent_id=pid,isshow=True).order_by('order')
        ser=Category(child,many=True)
        return Response({'mas':'success','data':ser.data,'code':200})

# class Course(APIView):
#     def get(self,request):
#         cid =request.query_params.get('cid')
#         if cid=="0":
#             course=CourseModel.objects.exclude(id=0).order_by('order')
#         else:
#             course=CourseModel.objects.filter(id=cid,isshow=True).order_by('order')
#         ser=CourseSerializer(course,many=True)
#         return Response({'mas':'success','data':ser.data,'code':200})
class CourseListView(ListAPIView):
    queryset = CourseModel.objects.all()
    serializer_class = CourseListSerializer

    pagination_class = CoursePage

    def get_queryset(self):
        direction=int(self.request.query_params.get('direction'))
        cate=int(self.request.query_params.get('cate'))
        level=int(self.request.query_params.get('level'))
        order=self.request.query_params.get('ordering')
        query=Q()
        if cate!=0:
            query&=Q(catetegory=cate)
        if direction>0 and cate==0:
            allcate=CategoryModel.objects.filter(parent=direction).values_list('id',flat=True)
            query&=Q(catetegory__in=allcate)
        if level>0:
            query&=Q(level=level)
        if order:
            return self.queryset.filter(query).order_by(order)
        else:
            return self.queryset.filter(query)

class CrousexqView(APIView):
    def get(self,request):
        id =request.query_params.get('id')
        course=CourseModel.objects.filter(id=id,isshow=True).first()
        course.read+=1
        course.save()
        ser=CourseSerializer(course)
        return Response({'mas':'success','data':ser.data,'code':200})

from rest_framework.generics import GenericAPIView
from django.core.files.storage import default_storage

class Upload(GenericAPIView):
    serializer_class =BannerImage
    def post(self, request):
        ser=self.get_serializer(data=request.data)
        if ser.is_valid():
            file=ser.validated_data.get('flie')
            name=default_storage.save(file.name,file)
            url=default_storage.url(name)
            return Response({'mas':'success','url':url})
        else:
            return Response(ser.errors)

class HotWordView(HaystackViewSet):
    index_models = [CourseModel]
    serializer_class = CourseIndexSer

    pagination_class = CoursePage

    def list(self, request, *args, **kwargs):
        text=request.query_params.get('text',"")
        if text:
            redistoll.hotadd('09ahot',text)

        data=super().list(request, *args,**kwargs).data
        for i in data['results']:
            i['cover']="http://127.0.0.1:8000/uploads"+i['cover']
        return Response(data)

class HotWord(APIView):
    def get(self,request):
        data=redistoll.hotget('09ahot')[:4]
        return Response(data)